package com.yunyike.app.util;

 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rop.request.UploadFile;
import com.yunyike.app.constants.CommonConstant;

 
public class UploadUtil {
     
    private static String uploadPath = CommonConstant.UPLOAD_IMG_PATH;
    private static String showImgPath = CommonConstant.SHOW_IMG_PATH;
 
    private  static Logger log = LoggerFactory.getLogger(UploadUtil.class);
    
    public static String uploadFile(UploadFile file,String imgName,Date date) throws Exception {
        FileOutputStream fos = null;
        InputStream inStream = null;
        String path = "";
        try{
        	log.info("begin：：upload");
        	inStream = new ByteArrayInputStream(file.getContent());
        	String dateStr = new SimpleDateFormat("yyyyMMdd").format(date);
        	String dirPath = uploadPath+dateStr;
        	File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String imgPath = dirPath+"/"+imgName+"."+file.getFileType();
//			if (new File(imgPath).exists()) {
//				imgName = imgName+"_1";
//				imgPath = dirPath+"/"+imgName+"."+file.getFileType();
//			}
        	log.info("imgPath：："+imgPath);
        	fos = new FileOutputStream(imgPath);

			byte[] b = new byte[1024];
			while((inStream.read(b)) != -1){
				fos.write(b);
			}
			path = showImgPath+dateStr+"/"+imgName+"."+file.getFileType();
			log.info("upload complete..."); 
        }catch(Exception e) { 
            e.printStackTrace();
            throw e;
        }finally{
            try { 
            	if(null!=inStream)inStream.close();
    			if(null!=fos)fos.close();
            }catch(Exception e2) { 
                e2.printStackTrace(); 
            } 
        } 
        return path;
    } 
 
     
}